/**
 * ESP32 库管理器
 * 负责管理在线库、依赖解析、缓存等功能
 */

class LibraryManager {
    constructor(state) {
        this.state = state;
        this.libraries = [];
        this.selectedLibrary = null;
        this.installedLibraries = {};
        this.cache = new LibraryCache();
        this.dependencyResolver = new DependencyResolver();
        // ESP-IDF组件注册表API基础URL
        this.registryApiUrl = 'https://api.components.espressif.com';
    }

    /**
     * 初始化库管理器
     */
    async init() {
        this.bindEvents();
        await this.initCache();
        console.log('Library Manager initialized');
    }

    /**
     * 初始化缓存
     */
    async initCache() {
        await this.cache.init();
        this.installedLibraries = await this.cache.getInstalledLibraries() || {};
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        // 模态框关闭按钮
        const closeLibraryModalBtn = document.getElementById('close-library-modal');
        if (closeLibraryModalBtn) {
            closeLibraryModalBtn.addEventListener('click', () => {
                this.closeModal();
            });
        }

        // 搜索库
        const librarySearchInput = document.getElementById('library-search');
        if (librarySearchInput) {
            let searchTimeout;
            librarySearchInput.addEventListener('input', (e) => {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    this.searchLibraries(e.target.value);
                }, 300); // 防抖处理
            });
        }

        // 类别筛选
        const libraryCategorySelect = document.getElementById('library-category');
        if (libraryCategorySelect) {
            libraryCategorySelect.addEventListener('change', () => {
                this.filterLibraries();
            });
        }

        // 芯片筛选
        const libraryChipSelect = document.getElementById('library-chip');
        if (libraryChipSelect) {
            libraryChipSelect.addEventListener('change', () => {
                this.filterLibraries();
            });
        }

        // 刷新库列表
        const refreshLibrariesBtn = document.getElementById('refresh-libraries');
        if (refreshLibrariesBtn) {
            refreshLibrariesBtn.addEventListener('click', async () => {
                await this.refreshLibraries();
            });
        }

        // 安装库
        const installLibraryBtn = document.getElementById('install-library');
        if (installLibraryBtn) {
            installLibraryBtn.addEventListener('click', async () => {
                if (this.selectedLibrary) {
                    await this.installLibrary(this.selectedLibrary);
                }
            });
        }
    }

    /**
     * 打开库管理模态框
     */
    openModal() {
        const modal = document.getElementById('library-manager-modal');
        if (modal) {
            modal.classList.remove('hidden');
            document.body.style.overflow = 'hidden';
            
            // 打开时自动聚焦搜索框
            setTimeout(() => {
                const searchInput = document.getElementById('library-search');
                if (searchInput) {
                    searchInput.focus();
                }
            }, 100);
        }
    }

    /**
     * 关闭库管理模态框
     */
    closeModal() {
        const modal = document.getElementById('library-manager-modal');
        if (modal) {
            modal.classList.add('hidden');
            document.body.style.overflow = 'auto';
        }
    }

    /**
     * 搜索库
     */
    async searchLibraries(query) {
        const searchIndicator = document.getElementById('search-indicator');
        if (searchIndicator) {
            searchIndicator.classList.remove('hidden');
        }

        try {
            if (!query.trim()) {
                this.displayLibraryList([]);
                return;
            }

            // 首先尝试从缓存获取
            let libraries = await this.cache.searchLibraries(query);
            
            // 如果缓存中没有或者缓存过期，则从API获取
            if (!libraries || libraries.length === 0 || this.isCacheExpired(libraries)) {
                libraries = await this.fetchLibrariesFromAPI(query);
                // 缓存搜索结果
                await this.cache.cacheLibraries(libraries);
            }
            
            this.libraries = libraries;
            this.displayLibraryList(libraries);
        } catch (error) {
            console.error('搜索库时出错:', error);
            this.displayLibraryList([]);
            
            // 显示错误信息
            const libraryListEl = document.getElementById('library-list');
            if (libraryListEl) {
                libraryListEl.innerHTML = `
                    <div class="p-4 text-center text-red-400">
                        <i class="fas fa-exclamation-circle text-2xl mb-2"></i>
                        <p>搜索库时出错: ${error.message}</p>
                        <p class="text-sm mt-2 text-gray-400">请检查网络连接后重试</p>
                    </div>
                `;
            }
        } finally {
            if (searchIndicator) {
                searchIndicator.classList.add('hidden');
            }
        }
    }

    /**
     * 检查缓存是否过期（超过1小时）
     */
    isCacheExpired(libraries) {
        if (!libraries || libraries.length === 0) return true;
        
        // 假设第一个库的缓存时间代表整个搜索结果的缓存时间
        const firstLibrary = libraries[0];
        if (!firstLibrary.cachedAt) return true;
        
        const cachedTime = new Date(firstLibrary.cachedAt).getTime();
        const currentTime = new Date().getTime();
        const oneHour = 60 * 60 * 1000; // 1小时毫秒数
        
        return (currentTime - cachedTime) > oneHour;
    }

    /**
     * 从API获取库列表
     */
    async fetchLibrariesFromAPI(query) {
        try {
            // 使用ESP-IDF组件注册表API
            // 注意：这是一个示例实现，实际API可能需要API密钥和不同的端点结构
            const response = await fetch(
                `${this.registryApiUrl}/components/search?q=${encodeURIComponent(query)}&limit=20`,
                {
                    headers: {
                        'Accept': 'application/json',
                        'User-Agent': 'ESP32-Dev-Tool/1.0'
                    }
                }
            );
            
            if (!response.ok) {
                throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
            }
            
            const data = await response.json();
            
            // 转换API响应格式为我们的内部格式
            const libraries = data.components ? data.components.map(component => ({
                id: component.name,
                name: component.name,
                version: component.version,
                description: component.description || '暂无描述',
                author: component.owner || 'Unknown',
                category: this.guessCategory(component.name, component.description),
                chip: this.extractChipCompatibility(component),
                downloads: component.download_count || 0,
                dependencies: component.dependencies || [],
                homepage: component.homepage,
                repository: component.repository,
                license: component.license,
                cachedAt: new Date().toISOString()
            })) : [];
            
            return libraries;
        } catch (error) {
            console.warn('ESP-IDF Registry API调用失败，使用模拟数据:', error);
            
            // 如果API调用失败，返回模拟数据
            return [
                {
                    id: 'bme280',
                    name: 'BME280 Sensor',
                    version: '1.2.3',
                    description: 'BME280温湿度气压传感器驱动库',
                    author: 'Espressif',
                    category: 'sensor',
                    chip: ['ESP32', 'ESP32-C3', 'ESP32-S3'],
                    downloads: 15000,
                    dependencies: [],
                    homepage: 'https://github.com/espressif/bme280',
                    repository: 'https://github.com/espressif/bme280.git',
                    license: 'Apache-2.0'
                },
                {
                    id: 'wifi-manager',
                    name: 'WiFi Manager',
                    version: '2.1.0',
                    description: '简化WiFi连接和管理的库',
                    author: 'Third Party',
                    category: 'wifi',
                    chip: ['ESP32', 'ESP32-C3'],
                    downloads: 8500,
                    dependencies: [],
                    homepage: 'https://github.com/espressif/wifi-manager',
                    repository: 'https://github.com/espressif/wifi-manager.git',
                    license: 'MIT'
                },
                {
                    id: 'mqtt-client',
                    name: 'MQTT Client',
                    version: '3.0.1',
                    description: '轻量级MQTT客户端实现',
                    author: 'Espressif',
                    category: 'communication',
                    chip: ['ESP32', 'ESP32-S3'],
                    downloads: 12200,
                    dependencies: ['wifi-manager@^2.0.0'],
                    homepage: 'https://github.com/espressif/mqtt-client',
                    repository: 'https://github.com/espressif/mqtt-client.git',
                    license: 'Apache-2.0'
                }
            ];
        }
    }

    /**
     * 根据库名称和描述猜测类别
     */
    guessCategory(name, description) {
        const nameLower = name.toLowerCase();
        const descLower = (description || '').toLowerCase();
        const combinedText = nameLower + ' ' + descLower;
        
        if (combinedText.includes('sensor') || 
            combinedText.includes('bme') || 
            combinedText.includes('bmp') || 
            combinedText.includes('dht') ||
            combinedText.includes('temperature') ||
            combinedText.includes('humidity')) {
            return 'sensor';
        }
        
        if (combinedText.includes('wifi') || combinedText.includes('wireless')) {
            return 'wifi';
        }
        
        if (combinedText.includes('bluetooth') || combinedText.includes('ble')) {
            return 'bluetooth';
        }
        
        if (combinedText.includes('display') || 
            combinedText.includes('lcd') || 
            combinedText.includes('oled') ||
            combinedText.includes('screen')) {
            return 'display';
        }
        
        if (combinedText.includes('communication') || 
            combinedText.includes('mqtt') || 
            combinedText.includes('http') ||
            combinedText.includes('tcp') ||
            combinedText.includes('udp')) {
            return 'communication';
        }
        
        return 'other';
    }

    /**
     * 提取芯片兼容性信息
     */
    extractChipCompatibility(component) {
        // 这里应该从组件元数据中提取芯片兼容性信息
        // 目前我们返回一个默认列表
        return ['ESP32', 'ESP32-C3', 'ESP32-S3'];
    }

    /**
     * 筛选库
     */
    filterLibraries() {
        const category = document.getElementById('library-category').value;
        const chip = document.getElementById('library-chip').value;
        
        let filteredLibraries = this.libraries;
        
        if (category) {
            filteredLibraries = filteredLibraries.filter(lib => lib.category === category);
        }
        
        if (chip) {
            filteredLibraries = filteredLibraries.filter(lib => lib.chip.includes(chip));
        }
        
        this.displayLibraryList(filteredLibraries);
    }

    /**
     * 刷新库列表
     */
    async refreshLibraries() {
        const searchQuery = document.getElementById('library-search').value;
        if (searchQuery.trim()) {
            // 清除缓存后重新搜索
            await this.cache.clearSearchCache();
            await this.searchLibraries(searchQuery);
        }
    }

    /**
     * 显示库列表
     */
    displayLibraryList(libraries) {
        const libraryListEl = document.getElementById('library-list');
        if (!libraryListEl) return;
        
        if (!libraries || libraries.length === 0) {
            libraryListEl.innerHTML = `
                <div class="p-6 text-center text-gray-500">
                    <i class="fas fa-book-open text-3xl mb-3"></i>
                    <p>未找到相关库</p>
                    <p class="text-sm mt-1">尝试使用其他关键词搜索</p>
                </div>
            `;
            return;
        }
        
        libraryListEl.innerHTML = libraries.map(lib => `
            <div class="library-item p-3 border-b border-gray-700 cursor-pointer hover:bg-gray-800 transition-all duration-200" 
                 data-id="${lib.id}">
                <div class="flex justify-between items-start">
                    <div class="font-medium text-sm">${lib.name}</div>
                    <div class="text-xs bg-blue-900 bg-opacity-50 px-2 py-1 rounded">
                        v${lib.version}
                    </div>
                </div>
                <div class="text-xs text-gray-400 mt-1 flex flex-wrap gap-1">
                    <span>${lib.author}</span>
                    <span>•</span>
                    <span>${lib.downloads.toLocaleString()} 下载</span>
                </div>
                <div class="text-xs text-gray-500 mt-2 line-clamp-2">${lib.description}</div>
                <div class="flex flex-wrap gap-1 mt-2">
                    ${lib.chip.slice(0, 3).map(chip => `
                        <span class="text-xs bg-gray-700 px-1.5 py-0.5 rounded">${chip}</span>
                    `).join('')}
                    ${lib.chip.length > 3 ? `
                        <span class="text-xs bg-gray-700 px-1.5 py-0.5 rounded">+${lib.chip.length - 3}</span>
                    ` : ''}
                </div>
            </div>
        `).join('');
        
        // 绑定库项点击事件
        document.querySelectorAll('.library-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const libId = e.currentTarget.getAttribute('data-id');
                const library = libraries.find(lib => lib.id === libId);
                if (library) {
                    this.selectLibrary(library);
                }
            });
        });
    }

    /**
     * 选择库
     */
    async selectLibrary(library) {
        this.selectedLibrary = library;
        this.displayLibraryDetail(library);
        
        // 更新安装按钮状态
        const installBtn = document.getElementById('install-library');
        if (installBtn) {
            installBtn.disabled = false;
            document.getElementById('selected-library-info').textContent = 
                `${library.name} v${library.version}`;
        }
        
        // 高亮选中的库项
        document.querySelectorAll('.library-item').forEach(item => {
            item.classList.remove('bg-gray-800', 'border-l-4', 'border-blue-500');
            if (item.getAttribute('data-id') === library.id) {
                item.classList.add('bg-gray-800', 'border-l-4', 'border-blue-500');
            }
        });
    }

    /**
     * 显示库详情
     */
    displayLibraryDetail(library) {
        const detailEl = document.getElementById('library-detail');
        if (!detailEl) return;
        
        detailEl.innerHTML = `
            <div class="mb-6">
                <div class="flex flex-col md:flex-row md:justify-between md:items-start gap-4">
                    <div>
                        <h2 class="text-xl font-bold">${library.name}</h2>
                        <div class="text-gray-400 mt-1 flex flex-wrap items-center gap-2 text-sm">
                            <span>v${library.version}</span>
                            <span>by ${library.author}</span>
                            <span class="flex items-center">
                                <i class="fas fa-download mr-1"></i>
                                ${library.downloads?.toLocaleString() || '0'}
                            </span>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <div class="bg-gray-800 px-3 py-1 rounded-full text-xs">
                            ${library.category}
                        </div>
                        <div class="bg-blue-900 bg-opacity-50 px-3 py-1 rounded-full text-xs">
                            ${library.license || 'Unknown'}
                        </div>
                    </div>
                </div>
                
                <p class="mt-4 text-gray-300">${library.description}</p>
                
                <div class="mt-4 flex flex-wrap gap-2">
                    ${library.chip.map(chip => `
                        <span class="bg-blue-900 bg-opacity-50 px-2 py-1 rounded text-xs">
                            ${chip}
                        </span>
                    `).join('')}
                </div>
                
                ${library.homepage || library.repository ? `
                <div class="mt-4 flex flex-wrap gap-3 text-sm">
                    ${library.homepage ? `
                    <a href="${library.homepage}" target="_blank" class="text-blue-400 hover:text-blue-300 flex items-center">
                        <i class="fas fa-home mr-1"></i> 主页
                    </a>
                    ` : ''}
                    ${library.repository ? `
                    <a href="${library.repository}" target="_blank" class="text-blue-400 hover:text-blue-300 flex items-center">
                        <i class="fab fa-github mr-1"></i> 源码
                    </a>
                    ` : ''}
                </div>
                ` : ''}
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <h3 class="font-semibold mb-3 flex items-center">
                        <i class="fas fa-file-code mr-2"></i>示例代码
                    </h3>
                    <div class="border border-gray-700 rounded-lg p-3 bg-gray-900 bg-opacity-50">
                        <pre class="text-xs overflow-x-auto"><code>// 示例代码
#include "driver/i2c.h"
#include "${library.name}.h"

void app_main() {
    // 初始化${library.name}
    ${library.name}_config_t config = ${library.name.toUpperCase()}_CONFIG_DEFAULT();
    ${library.name}_init(&config);
    
    // 使用库功能
    // ...
}</code></pre>
                    </div>
                </div>
                
                <div>
                    <h3 class="font-semibold mb-3 flex items-center">
                        <i class="fas fa-code-branch mr-2"></i>依赖关系
                    </h3>
                    <div class="border border-gray-700 rounded-lg p-3 bg-gray-900 bg-opacity-50">
                        ${library.dependencies && library.dependencies.length > 0 ? 
                            `<ul class="text-sm space-y-2">
                                ${library.dependencies.map(dep => `
                                    <li class="flex items-center">
                                        <i class="fas fa-arrow-right mr-2 text-gray-500"></i>
                                        <span>${dep}</span>
                                    </li>
                                `).join('')}
                            </ul>` : 
                            `<p class="text-gray-500 text-sm">无依赖</p>`
                        }
                    </div>
                    
                    <h3 class="font-semibold mt-4 mb-3 flex items-center">
                        <i class="fas fa-chart-line mr-2"></i>统计信息
                    </h3>
                    <div class="border border-gray-700 rounded-lg p-3 bg-gray-900 bg-opacity-50">
                        <div class="text-sm space-y-2">
                            <div class="flex justify-between">
                                <span class="text-gray-400">下载量</span>
                                <span>${library.downloads?.toLocaleString() || 'N/A'}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-400">版本</span>
                                <span>v${library.version}</span>
                            </div>
                            <div class="flex justify-between">
                                <span class="text-gray-400">许可证</span>
                                <span>${library.license || 'Unknown'}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 安装库
     */
    async installLibrary(library) {
        try {
            // 显示安装进度
            const installBtn = document.getElementById('install-library');
            const originalText = installBtn.innerHTML;
            installBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>安装中...';
            installBtn.disabled = true;
            
            // 解析依赖
            const dependencyTree = await this.dependencyResolver.resolveDependencies(library);
            
            // 下载库文件
            await this.downloadLibraryFiles(library, dependencyTree);
            
            // 更新项目配置
            await this.updateProjectConfiguration(library, dependencyTree);
            
            // 缓存已安装的库
            this.installedLibraries[library.id] = {
                ...library,
                installedAt: new Date().toISOString()
            };
            await this.cache.saveInstalledLibraries(this.installedLibraries);
            
            // 显示成功消息
            if (window.esp32DevTool && window.esp32DevTool.ui) {
                window.esp32DevTool.ui.showAlert(`库 ${library.name} 安装成功！`, 'success');
            }
            
            console.log(`库 ${library.name} 安装成功`);
        } catch (error) {
            console.error('安装库时出错:', error);
            if (window.esp32DevTool && window.esp32DevTool.ui) {
                window.esp32DevTool.ui.showAlert(`安装库失败: ${error.message}`, 'error');
            }
        } finally {
            // 恢复按钮状态
            const installBtn = document.getElementById('install-library');
            installBtn.innerHTML = '<i class="fas fa-download mr-2"></i>安装库';
            installBtn.disabled = false;
        }
    }

    /**
     * 下载库文件
     */
    async downloadLibraryFiles(library, dependencyTree) {
        // 模拟下载过程
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 实际实现中，这里会:
        // 1. 从registry下载库文件
        // 2. 解压到项目components目录
        // 3. 处理依赖库的下载和解压
        
        console.log(`下载库文件: ${library.name}`);
        console.log('依赖树:', dependencyTree);
    }

    /**
     * 更新项目配置
     */
    async updateProjectConfiguration(library, dependencyTree) {
        // 模拟更新配置过程
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 实际实现中，这里会:
        // 1. 更新CMakeLists.txt的COMPONENT_REQUIRES
        // 2. 生成或更新dependencies.lock文件
        // 3. 更新项目状态
        
        console.log(`更新项目配置: ${library.name}`);
    }
}

/**
 * 库缓存管理器
 */
class LibraryCache {
    constructor() {
        this.db = null;
    }

    /**
     * 初始化IndexedDB
     */
    async init() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open('ESP32LibraryCache', 2); // 版本号增加以触发升级
            
            request.onerror = () => {
                reject(new Error('无法打开IndexedDB'));
            };
            
            request.onsuccess = (event) => {
                this.db = event.target.result;
                resolve();
            };
            
            request.onupgradeneeded = (event) => {
                const db = event.target.result;
                
                // 创建库对象存储
                if (!db.objectStoreNames.contains('libraries')) {
                    const libraryStore = db.createObjectStore('libraries', { keyPath: 'id' });
                    libraryStore.createIndex('name', 'name', { unique: false });
                    libraryStore.createIndex('category', 'category', { unique: false });
                    libraryStore.createIndex('searchTerm', 'searchTerm', { unique: false });
                    libraryStore.createIndex('lastAccessed', 'lastAccessed', { unique: false });
                }
                
                // 创建已安装库对象存储
                if (!db.objectStoreNames.contains('installed')) {
                    const installedStore = db.createObjectStore('installed', { keyPath: 'id' });
                }
                
                // 创建搜索历史对象存储
                if (!db.objectStoreNames.contains('searchHistory')) {
                    const searchStore = db.createObjectStore('searchHistory', { keyPath: 'term' });
                    searchStore.createIndex('timestamp', 'timestamp', { unique: false });
                }
            };
        });
    }

    /**
     * 搜索库
     */
    async searchLibraries(query) {
        if (!this.db) return [];
        
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['libraries'], 'readonly');
            const store = transaction.objectStore('libraries');
            const index = store.index('searchTerm');
            const request = index.getAll(query.toLowerCase());
            
            request.onsuccess = (event) => {
                const libraries = event.target.result || [];
                resolve(libraries);
            };
            
            request.onerror = () => {
                reject(new Error('搜索库时出错'));
            };
        });
    }

    /**
     * 缓存库列表
     */
    async cacheLibraries(libraries) {
        if (!this.db) return;
        
        const transaction = this.db.transaction(['libraries'], 'readwrite');
        const store = transaction.objectStore('libraries');
        
        const searchTerm = libraries[0]?.searchTerm || '';
        
        for (const library of libraries) {
            // 添加搜索相关字段
            const libraryWithSearch = {
                ...library,
                searchTerm: searchTerm,
                lastAccessed: new Date().toISOString()
            };
            store.put(libraryWithSearch);
        }
    }

    /**
     * 获取已安装的库
     */
    async getInstalledLibraries() {
        if (!this.db) return {};
        
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['installed'], 'readonly');
            const store = transaction.objectStore('installed');
            const request = store.getAll();
            
            request.onsuccess = (event) => {
                const libraries = event.target.result || [];
                const result = {};
                libraries.forEach(lib => {
                    result[lib.id] = lib;
                });
                resolve(result);
            };
            
            request.onerror = () => {
                reject(new Error('获取已安装库时出错'));
            };
        });
    }

    /**
     * 保存已安装的库
     */
    async saveInstalledLibraries(libraries) {
        if (!this.db) return;
        
        const transaction = this.db.transaction(['installed'], 'readwrite');
        const store = transaction.objectStore('installed');
        
        // 清除旧数据
        store.clear();
        
        // 保存新数据
        Object.values(libraries).forEach(lib => {
            store.put(lib);
        });
    }

    /**
     * 清除搜索缓存
     */
    async clearSearchCache() {
        if (!this.db) return;
        
        return new Promise((resolve, reject) => {
            const transaction = this.db.transaction(['libraries'], 'readwrite');
            const store = transaction.objectStore('libraries');
            const request = store.clear();
            
            request.onsuccess = () => {
                resolve();
            };
            
            request.onerror = () => {
                reject(new Error('清除搜索缓存时出错'));
            };
        });
    }
}

/**
 * 依赖解析器
 */
class DependencyResolver {
    /**
     * 解析依赖
     */
    async resolveDependencies(library) {
        // 模拟依赖解析过程
        await new Promise(resolve => setTimeout(resolve, 300));
        
        // 实际实现中，这里会:
        // 1. 解析库的依赖关系
        // 2. 递归检查子依赖
        // 3. 检测版本冲突
        // 4. 生成依赖树
        
        return {
            library: library,
            dependencies: library.dependencies || [],
            resolved: true
        };
    }
}

// 导出类
export { LibraryManager, LibraryCache, DependencyResolver };